<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <day04Tr
          v-for="(item, index) in goodList"
          :key="index"
          :uname="item.name"
          :price="item.price"
          :num="item.num"
          :checked="item.checked"
          :index="index"
          @checkedAll="checkedAll"
          @del="del"
          @sum="sum"
          @sub="sub"
        ></day04Tr>
        <!-- @change="change" -->
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">{{ zprice }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import day04Tr from './components/day04-03tr.vue'
export default {
  data() {
    return {
      goodList: [
        {
          name: '诸葛亮',
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: '蔡文姬',
          price: 1500,
          num: 1,
          checked: true,
        },
        {
          name: '妲己',
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: '鲁班',
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
      zprice: 0,
    }
  },
  components: {
    day04Tr,
  },
  methods: {
    del(trindex) {
      console.log(1)
      this.goodList.splice(trindex, 1)
    },
    sum(trindex, trnum, trprice) {
      console.log('+')
      this.goodList[trindex].num = trnum + 1
    },
    sub(trindex, trnum) {
      console.log('-')
      if (this.goodList[trindex].num < 1) return
      this.goodList[trindex].num = trnum - 1
    },
    checkedAll(checkedTr, index) {
      // console.log(checkedTr, index)
      this.goodList[index].checked = checkedTr
    },
  },
  computed: {
    isAll: {
      get() {
        // console.log('选中')
        return this.goodList.every((item) => item.checked)
      },
      // 试图改变 isAll 时触发set
      set(val) {
        console.log(val)
        this.goodList.forEach((item) => (item.checked = val))
      },
    },
  },
  watch: {
    goodList: {
      immediate: true,
      deep: true,
      handler() {
        this.zprice = this.goodList
          .filter((item) => item.checked)
          .reduce((prv, item) => prv + item.price * item.num, 0)
      },
    },
  },
}
</script>

<style>
table {
  text-align: center;
}
</style>
